package com.example.demoofimagedownloadapp.model;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;

import com.example.demoofimagedownloadapp.R;
import com.example.demoofimagedownloadapp.bean.DataBean;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class MusicModel {
    private static final String TAG = MusicModel.class.getName();
    private static final int MUSIC_MINTIME_SECOND = 30;
    private static final int MUSIC_MINSIZE = 1024*1024;
    private Context mContext;
    public List<DataBean> mMediaList = null;
    private int playingId = 0;
//    private List<AlbumBean> mAlbumList = new ArrayList<>();
    public MusicModel (Context context) {
        this.mContext = context;
    }

    @SuppressLint("Range")
    public List<DataBean> getAllMediaList(Context context, String selection) throws FileNotFoundException {
        Cursor cursor = null;
        List<DataBean> mediaList = new ArrayList<>();
        try {
            cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DISPLAY_NAME,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.SIZE,
                            MediaStore.Audio.Media.ALBUM_ID
                    },
                    selection, null, MediaStore.Audio.Media.DATE_ADDED + " DESC");
            if(cursor == null) {
                Log.d(TAG, "The getMediaList cursor is null.");
                return mediaList;
            }
            int count= cursor.getCount();
            if(count <= 0) {
                Log.d(TAG, "The getMediaList cursor count is 0.");
                return mediaList;
            }
            mediaList = new ArrayList<DataBean>();
            DataBean mediaEntity = null;

            while (cursor.moveToNext()) {
                mediaEntity = new DataBean();
                mediaEntity.id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                mediaEntity.setDuration(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
                mediaEntity.size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                if(!checkIsMusic(mediaEntity.getDuration(), mediaEntity.size)) {
                    mediaEntity = null;
                    continue;
                }
                mediaEntity.setAlbums(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
                mediaEntity.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
                mediaEntity.setSongName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
                mediaEntity.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
                mediaEntity.setSongPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
                mediaEntity.setAlbumId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
//                mediaEntity.setAlbumArt(getAlbumArt(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))));
                mediaList.add(mediaEntity);
            }
        } catch (Exception e) {

        } finally {
            if(cursor != null) {
                cursor.close();
            }
        }
        Log.d(TAG, "getAllMediaList: DONE/"+mediaList);
        mMediaList = mediaList;
//        getAlbum();
        return mediaList;
    }

    private boolean checkIsMusic(int time, long size) {
        if(time <= 0 || size <= 0) {
            return  false;
        }

        time /= 1000;
        int minute = time / 60;
        //	int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        if (minute <= 0 && second <= MUSIC_MINTIME_SECOND ) {
            return false;
        }
        if ( size <= MUSIC_MINSIZE) {
            return false;
        }
        return true;
    }

    @SuppressLint("Range")
    public Bitmap getAlbumArt(int album_id) {
        String mUriAlbumArt = "content://media/external/audio/albumart";
        Bitmap bm = null;
        Uri uri = ContentUris.withAppendedId(Uri.parse(mUriAlbumArt), album_id);
        ParcelFileDescriptor pfd = null;
        FileDescriptor fd = null;
        try {
            pfd = mContext.getContentResolver().openFileDescriptor(uri, "r");
        }catch (FileNotFoundException e) {
            Log.d(TAG, "getAlbum: "+e.getStackTrace());
        }

        if(pfd != null) {
            fd = pfd.getFileDescriptor();
            bm = BitmapFactory.decodeFileDescriptor(fd);
        }


        if (bm != null) {
//            bm = BitmapFactory.decodeFile(album_art);
        } else {
            Log.d(TAG, "getAlbumArt: is NULL");
            bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher_copy);
        }
        Log.d(TAG, "getAlbumArt: "+album_id + "/"+ bm);
        return bm;
    }
//    @SuppressLint("Range")
//    private List<AlbumBean> getAlbum() throws FileNotFoundException {
//        List<AlbumBean> list = new ArrayList<>();
//        String mUriAlbums = "content://media/external/audio/albums";
//        String mUriAlbumArt = "content://media/external/audio/albumart";
//        String[] projection = new String[] {
//                MediaStore.Audio.Albums.ALBUM_ID,
//        };
//
//        Cursor cur = mContext.getContentResolver().query(
//                Uri.parse(mUriAlbums),
//                projection, null, null, null);
//        AlbumBean albumBean = null;
//
//        while (cur.moveToNext()) {
//            albumBean = new AlbumBean();
//            albumBean.albumItemId = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID));
//            Log.d(TAG, "getAlbum: "+albumBean.albumItemId);
//            FileDescriptor fd = null;
//            if(albumBean.albumItemId < 0){
//
//            } else {
//                Uri uri = ContentUris.withAppendedId(Uri.parse(mUriAlbumArt), albumBean.albumItemId);
//                ParcelFileDescriptor pfd = null;
//                try {
//                    pfd = mContext.getContentResolver().openFileDescriptor(uri, "r");
//                }catch (FileNotFoundException e) {
//                    Log.d(TAG, "getAlbum: "+e.getStackTrace());
//                }
//
//                if(pfd != null) {
//                    fd = pfd.getFileDescriptor();
//                    albumBean.albumItemArt = BitmapFactory.decodeFileDescriptor(fd);
//                }
//            }
//
//            list.add(albumBean);
////            albumBean = null;
//        }
//        cur.close();
//        cur = null;
//        Log.d(TAG, "getAlbum: "+list);
//        return list;
//    }
//
//    class AlbumBean {
//        public int albumItemId;
//        public Bitmap albumItemArt;
//    }

    public int getPlayingId() {
        return playingId;
    }

    public void setPlayingId(int playingId) {
        this.playingId = playingId;
    }

    public void setPrevious(){
        if (mMediaList != null) {
            if (playingId - 1>=0){
                playingId = playingId-1;
            }else {
                playingId = mMediaList.size() - 1;
            }
        }
    }
    public void setNext(){
        if (mMediaList != null) {
            playingId = (playingId+1)%mMediaList.size();
        }
    }
    public String getSourcePath(){
        if (mMediaList == null) {
            return null;
        }
        return mMediaList.get(playingId).getSongPath();
    }
}
